/**
 * 角色列表
 */
layui.config({
    base: '/js/layui_exts/' //假设这是你存放拓展模块的根目录
}).extend({ //设定模块别名
        authtree: 'authtree'
});

$(function () {
  layui.use(['table', 'layer', 'element', 'form', 'authtree'], function () {
    let table = layui.table, layer = layui.layer, element = layui.element, authtree = layui.authtree, form = layui.form;

    //初始化权限树数
    PermissionTree.init(layui);
    const permissionTreeSetting = {elem: '#permission-tree', id:'permission'};

    let toEditTab = function (setting) {
      element.tabChange('mainTab', 2);
      $('#editRoleLi').removeClass('layui-hide');

      if(!setting.defaultFormData){setting.defaultFormData = {
          roleName: null,
          code:null,
          descpt:null
      };}
        if(!setting.defaultTreeData){setting.defaultTreeData = [];}

        //设置默认值
      let setDefault = function(){
          //表单赋初值
          form.val('roleForm', setting.defaultFormData);
          //权限树更新
          console.log(authtree);
          PermissionTree.render(permissionTreeSetting, setting.defaultTreeData);
      };

        setDefault();



      //监听表单提交
      form.on('submit(roleSubmit)', function (data) {
        //TODO 校验表单
        let field = data.field;
        console.log('field', field);

        //去除未改动的表单数据
        let defaultFormData = setting.defaultFormData;
        let roleData = {};
        for (let key in field) {
          if (defaultFormData[key] != field[key]) {
            roleData[key] = field[key];
          }
        }
        if(defaultFormData.id){
            roleData.id = defaultFormData.id;
        }
        delete roleData.perms;
        // console.log('roleData', roleData);

        //读取权限数据值
          let checkData = authtree.getChecked(permissionTreeSetting.elem);
        // console.log('checkedData', checkData);
        // let checkData = treeData2List(tree.getChecked('permission-tree'));
        if (checkData.length == 0) {
          layer.msg('不合法的权限', {icon: 4});
          return false;
        }
        //提取权限id
        let permissionId = checkData ;
        // for (let i in checkData) {
        //   permissionId.push(checkData[i].id);
        // }

          roleData.rolePermIds = permissionId.join(',');

        //发送请求
        let url;
        switch (setting.type) {
          case 'edit':
            url = '/auth/setRole';
            break;
          case 'add':
            url = '/auth/addRole';
            break;
          default:
            return;
        }
        $.ajax({
          url: url,
          type: 'POST',
          data: roleData,
          success: (res) => {
            if (res.code == 0) {
              // layer.msg('ok');
              if(setting.currentTarget){
                setting.currentTarget.update(roleData);
              }
              layer.msg('成功', {icon: 1});
            } else {
              layer.msg(res.status || '发生了错误', {icon: 4});
            }
          },
          error: (res) => {
            layer.msg(res.status || '发生了错误', {icon: 4});
          }
        });

          return false;
      });

        //重置
        $('#roleReset').on('click', function () {
            setDefault()
        })

    };


    //渲染表格
    let tableIns;
    let tableData;
    tableIns = table.render({
      elem: '#roleTable',
      url: '/auth/getRoleList',
      method: "POST",
      loading: true,
      // width: '100%',
      page: {
        layout: ['refresh', 'prev', 'page', 'next', 'count'],
      },
      even: true, //隔行背景
      size: 'lg', //大尺寸的表格
      cellMinWidth: 120,
      limit: 15,
      cols: [[
        {field: 'code', title: '角色代码'},
        {field: 'roleName', title: '角色名字'},
        {field: 'descpt', title: '角色描述',},
        {field: 'insertTime', title: '添加时间'},
        {fixed: 'right', title:"操作", align: 'center', toolbar: '#roleTableLineToolLayer'}

      ]],
      request: {
        pageName: 'page', //页码的参数名称，默认：page
        limitName: 'size' //每页数据量的参数名，默认：limit
      },
      parseData: function (res) { //res 即为原始返回的数据
        let count = res.data && res.data.length || 0;
        tableData = res.data;
        return {
          "code": res.code, //解析接口状态
          "msg": res.msg, //解析提示文本
          "count": count, //解析数据长度
          "data": res.data
        };
      }

    });

    //行工具事件
    table.on('tool(roleTable)', function (obj) {
      let data = obj.data; //获得当前行数据
      let layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
      // var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）
      console.log('data', data);
      if (layEvent === 'del') { //删除
        layer.confirm('确认删除？', function (index) {
          layer.close(index);
          //向服务端发送删除指令
          $.ajax({
            url: '/auth/delRole',
              type: 'POST',
            data: {roleId: data.id},
            success: (res) => {
              if (res.code == 0) {
                obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                layer.msg('成功', {icon: 1});
              } else {
                layer.msg(res.msg, {icon: 4});
              }
            },
            error: (res) => {
              layer.msg(res.status || '发生了错误', {icon: 4});
            }
          });
        });
      } else if (layEvent === 'edit') {
        //do something
        // $('li#editRoleLi').removeClass();

        //读取角色权限信息
        $.ajax({
          url: '/auth/selectPermissionIdOfRole',
          data: {id: data.id},
          success: (res) => {
            if (res.code == 0) {
              toEditTab({
                type: 'edit',
                defaultFormData: data,
                defaultTreeData: res.data,
                currentTarget: obj //当前事件行对象
              })
            } else {
              layer.msg(res.status || '发生了错误', {icon: 4});
            }
          },
          error: (res)=>{
            layer.msg(res.status || '发生了错误', {icon: 4});
          }
        })

        //同步更新缓存对应的值
        // obj.update({
        //   username: '123'
        //   ,title: 'xxx'
        // });
      }
    });

    //新建角色按钮
    $('#addRoleButton').on('click', function () {
      toEditTab({
        type: 'add',
        currentTarget: {
          update:function (field) {
            console.log('tableIns', tableIns);
            let data = tableData;
            if(!data){return;}
            data.push(field);
            tableIns.reload({
              data: data
            })
          }
        } //当前事件行对象
      })
    })
  });
});


